package com.csdj.x315springboot.common;

import com.csdj.x315springboot.service.RedisService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    private RedisService redisService;

    public LoginInterceptor(RedisService redisService){
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uid = request.getHeader(CacheConstant.HEADER_UID);
        if(StringUtils.hasText(uid)){
            String token = request.getHeader(CacheConstant.HEADER_TOKEN);
            if(StringUtils.hasText(token)){
                //从redis get token
                String cacheToken = redisService.getObject(CacheConstant.TOKEN_PREFIX+uid);
                if(token.equals(cacheToken)){
                    return true;
                }
            }
        }
        response.setContentType("application/json;charset=utf-8");
        WebResult webResult = new WebResult(ErrorCodeConstant.NO_LOGIN);
        ObjectMapper om = new ObjectMapper();
        String result = om.writeValueAsString(webResult);
        response.getWriter().write(result);
        response.flushBuffer();
        return false;
    }
}
